#!/usr/bin/ruby

MAX=50
INTERVAL=0.025

a=ARGV.collect { |x| Integer(x) }
a=Array.new(MAX,MAX).collect { |x| Integer( rand() * x ) } if a.length() == 0

def print_array( a )
  system "clear"
  MAX.downto(1) {
    |line|
    for v in a do
      print v>=line ? '|' : ' '
    end
    print "\n"
  }
  sleep INTERVAL
end

def compare( a, b )
  return a < b
end

def swap( array, a, b )
  t = array[a]
  array[a] = array[b]
  array[b] = t
  print_array( array )
end

def cocktail_sort( array )
  print_array(array)
  last=array.size()-1
  while true
    swapped = false
    for i in 0..last-1 do
      if not compare(array[i],array[i+1]) then
	if array[i] != array[i+1] then
	  swap(array, i, i+1)
	  print_array(array)
	  swapped = true
	end
      end
    end
    break if not swapped
    swapped = false
    (last-1).downto(1) {
      |i|
      if not compare(array[i-1],array[i]) then
	if array[i-1] != array[i] then
	  swap(array, i, i-1)
	  print_array(array)
	  swapped = true
	end
      end
    }
    break if not swapped
  end
  return array
end

a=cocktail_sort(a)
